package pro.lingwu.station.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pro.lingwu.station.dto.db.Admin;
import pro.lingwu.station.service.AdminService;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;


/**
 * @author @lingwu
 * @date created in 2021/11/16
 */
@Api(tags = "Admin")
@RestController
public class AdminController {

    private final AdminService adminService;

    public AdminController(AdminService adminService) {
        this.adminService = adminService;
    }

    @ApiOperation(value = "增加管理员")
    @PostMapping("/admin")
    @ApiResponses(
            @ApiResponse(code = 200, response = Admin.class, message = "ok")
    )
    public ResponseEntity<?> regAdmin(@RequestBody @Valid Admin admin){
        // 表单验证pass
        adminService.addAdmin(admin);
        return ResponseEntity.ok(admin);
    }

    @ApiOperation(value = "管理员登录")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = Admin.class),
            @ApiResponse(code = 404, message = "not found")
    })
    @GetMapping("/admin/{account}")
    public ResponseEntity<?> adminSignIn(@PathVariable String account,
                                         String password, HttpServletRequest request){
        Admin admin = adminService.signIn(account, password, request);
        if (admin == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(admin);
    }

    @ApiOperation(value = "修改管理员信息")
    @PutMapping("/admin/{account}")
    public ResponseEntity<?> updateAdmin(@PathVariable String account, @RequestBody Admin admin){
        admin.setAccount(account);
        adminService.updateAdmin(admin);
        return ResponseEntity.ok("ok");
    }

    @ApiOperation(value = "获取所有管理员")
    @GetMapping("/admin")
    public ResponseEntity<?> getAdmins(int start, int size){
        return ResponseEntity.ok(adminService.getAdmins(start, size));
    }

    @ApiOperation(value = "删除管理员")
    @DeleteMapping("/admin/{account}")
    public ResponseEntity<?> rmAdmin(@PathVariable String account){
        adminService.rmAdmin(account);
        return ResponseEntity.ok("ok");
    }

}
